const db = require('../db/index')

exports.getUser = (req,res)=>{
    const { name } = req.body
    let sql = 'select id, username, sex, name, email, phone, birthday, role, create_at from user where 1=1';
    let params = [];

    if (name) {
        sql += ' and name like ?';
        params.push(`%${name}%`);
    }

    db.query(sql, params, (err,result)=>{
        if(err){
            return res.send({
                status: 1,
                msg: '查询失败了'+err
            })
        }
        return res.send({
            status: 0,
            msg: '查询成功',
            data: result
        })
    })
}

exports.updateUser = (req, res) => {
    const { id, username, sex, name, email, phone, birthday, role } = req.body;
    console.log(req.body)

    // 检查所有必需字段
    if (!id || !username || !sex || !name || !email || !phone || !birthday || !role) {
        return res.status(400).send({
            status: 1,
            msg: '信息不能为空！'
        });
    }

    // TODO: 添加更多的字段验证，例如 email 格式，phone 格式，id 是否为有效数字

    let sql = 'UPDATE user SET username=?, sex=?, name=?, email=?, phone=?, birthday=?, role=? WHERE id=?';
    let sqlParams = [username, sex, name, email, phone, birthday, role, id];

    db.query(sql, sqlParams, (err, result) => {
        if (err) {
            console.error('数据库更新错误:', err);
            return res.status(500).send({
                status: 1,
                msg: '更新失败了，请稍后再试'
            });
        }

        if (result.affectedRows === 0) {
            return res.status(404).send({
                status: 1,
                msg: '用户不存在，更新失败'
            });
        }

        return res.status(200).send({
            status: 0,
            msg: '更新成功'
        });
    });
}

exports.deleteUser = (req, res) => {
    const { id } = req.body;
    console.log(req.body)
    if (!id) {
        return res.status(400).send({
            status: 1,
            msg: '用户ID不能为空！'
        });
    }

    db.query('DELETE FROM user WHERE id=?', id, (err, result) => {
        if (err) {
            console.error('数据库删除错误:', err);  
            return res.status(500).send({
                status: 1,
                msg: '删除失败了，请稍后再试'
            });
        }

        if (result.affectedRows === 0) {
            return res.status(404).send({
                status: 1,
                msg: '用户不存在，删除失败'
            });
        }

        return res.status(200).send({
            status: 0,
            msg: '删除成功'
        });
    });
}